﻿
#include "appconfig.h"
#include <QFile>
#include <QDebug>

SINGLETON_IMPL(AppConfig)

AppConfig::AppConfig()
{
    init();
}

QString AppConfig::userName()
{
    QMutexLocker locker(&m_userMutex);
    return m_user["user_name"].toString();
}

void AppConfig::setUserName(const QString& name)
{
    {
        QMutexLocker locker(&m_userMutex);
        m_user["user_name"] = name;
    }
    saveConfig();
}

QString AppConfig::userPassword()
{
    QMutexLocker locker(&m_userMutex);
    return m_user["user_password"].toString();
}

void AppConfig::setUserPassword(const QString& passwd)
{
    {
        QMutexLocker locker(&m_userMutex);
        m_user["user_password"] = passwd;
    }
    saveConfig();
}

int AppConfig::isRemainPassword()
{
    QMutexLocker locker(&m_userMutex);
    return m_user["remain_password"].toInt(0);
}

void AppConfig::remainPassword(int state)
{
    // 需要在加锁时考虑锁作用域，否则造成死锁
    {
        QMutexLocker locker(&m_userMutex);
        m_user["remain_password"] = state;
    }
    saveConfig();
}


int AppConfig::isRemainCustom()
{
    QMutexLocker locker(&m_userMutex);
    return m_user["remain_custom"].toInt(0);
}

void AppConfig::remainCustom(int state)
{
    {
        QMutexLocker locker(&m_userMutex);
        m_user["remain_custom"] = state;
    }
    saveConfig();
}

void AppConfig::init()
{
    // 1. 读取 sys.json
    QFile f("./config/sys.json");
    if(f.open(QIODevice::ReadOnly | QIODevice::Text)) {
        m_sys = QJsonDocument::fromJson(f.readAll()).object();
        qInfo() << m_sys;

        f.close();
    }

    // 2. 读取 user.json
    f.setFileName("./config/user.json");
    if(f.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMutexLocker locker(&m_userMutex);
        m_user = QJsonDocument::fromJson(f.readAll()).object();
        qInfo() << m_user;

        f.close();
    }
}

void AppConfig::saveConfig()
{
    QFile f("./config/user.json");
    if(f.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMutexLocker locker(&m_userMutex);
        auto d = QJsonDocument(m_user).toJson();
        f.write(d);

        f.close();
    }
}
